#include "engine.h"
#include "font.h"
#include "Render/rendersystem.h"
#include "core/log.h"

	hashcontainer_t<font_t,1024,1024>	fonts;

	void font_t::load_from(stringhash name, file_t* file)
	{
		uint8 width[256];

		uint8 dummy;
		uint32 map_width, map_height, cell_width, cell_height;

		file->read((char*)&map_width,4);
		file->read((char*)&map_height,4);
		file->read((char*)&cell_width,4);
		file->read((char*)&cell_height,4);
		file->read((char*)&dummy, 1);
		file->read((char*)&width[0], 256);

		int cell_count_horizontal=map_width/cell_width;
		int cell_count_vertical=map_height/cell_height;

		start_index=dummy;
		num_chars=256;
		texture_width=(float)map_width;
		texture_height=(float)map_height;
		for (int i=0;i<cell_count_horizontal*cell_count_vertical;i++)
		{
			buv[i].x=((float)(i%cell_count_horizontal))/cell_count_horizontal;
			buv[i].y=((float)(i/cell_count_horizontal))/cell_count_vertical;
			buv[i].z=(float)width[start_index+i]/texture_width;
			buv[i].w=1.0f/cell_count_vertical;
		}

		texture=RSYS->get_texture(name);
		mono=false;
	}

	void load_font(stringhash name, file_t* file, uint32 package_id)
	{
		font_t* font=fonts.allocate(name);
		if (font)
			font->load_from(name, file);
	}

	void flush_fonts()
	{
		fonts.flush();
	}

	font_t* get_font(stringhash name)
	{
		font_t* font=fonts.get(name);
		if (!font)
		{
			file_t f;
			if (f.open((string(name.c_str())+".dat").c_str(), "rb"))
			{
				load_font(name, &f, 0);
				f.close();
				font=fonts.get(name);
			} else
			{
				log_t::log(_str("font missing: %s\n", name.c_str()));
				font=fonts.allocate(name);
				memset(font, 0, sizeof(font_t));
			}
		}

		return font;
	}

